package com.monas.server.parser;

import java.io.File;

import com.monas.server.MonasConstants;
import com.monas.server.MonasProperties;
import com.monas.server.database.MonasDatabase;

/**
 * 
 * @author ekowahyudi
 * 
 */
public class MonasLoader implements MonasConstants {

	private final MonasDatabase database;

	public MonasLoader(MonasDatabase database) {
		this.database = database;
	}

	public void loadFiles() {
		String folder = MonasProperties.getDBProperty(DB_TRANSFER_DIR);
		String loaderDir = MonasProperties.getDBProperty(DB_LOADER_DIR);

		MonasParserFactory factory = new MonasParserFactory();

		File dir = new File(folder);
		for (File file : dir.listFiles()) {
			if (isRawFile(file.getName())) {
				try {
					MonasParser parser = factory.getParser(getPrefix(file
							.getName()));
					parser.readFile(file.getAbsolutePath());
					database.insertTable(parser.getTableName(), file.getName(),
							parser.getHeaders(), parser.getRecords());
					
					// Move into folder loader
					file.renameTo(new File(loaderDir, file.getName()));
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}
	}

	private String getPrefix(String name) {
		String[] fields = name.split("\\_");
		if (fields.length > 1) {
			return fields[1];
		}
		return "";
	}

	private boolean isRawFile(String name) {
		return !name.startsWith(".") && name.endsWith(".txt")
				&& name.indexOf('_') > 0;
	}

	public static void main(String[] args) {

		MonasDatabase database = MonasDatabase.getInstance();

		try {
			MonasLoader loader = new MonasLoader(database);
			loader.loadFiles();
		} finally {
			database.close();
		}
	}

}
